<?php


namespace app\api\controller;

use app\common\model\CompanyModel;
use app\common\model\UserModel;
use app\common\model\UserVisitModel;
use app\common\service\ReturnCodeService;
use think\Db;
use Firebase\JWT\JWT;

/**
 * 用户中心
 * Class User
 * @package app\api\controller
 */
class User extends Base
{
    protected $userModel;
    protected $userVisitModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = new UserModel();
        $this->userVisitModel = new UserVisitModel();
        $this->companyModel = new CompanyModel();
    }

    /**
     * showdoc
     * @catalog BOSS系统/用户中心
     * @title 注册
     * @description
     * @method POST
     * @url api/User/register
     * @param company_id 必选 int 企业ID
     * @param app_sn 必选 int 应用编号
     * @param client 必选 int 终端1微信小程序 2支付宝小程序 3百度小程序
     * @param telphone 必选 string 手机号
     * @param realname 可选 string 姓名
     * @param sex 可选 int 性别0未知1男2女
     * @param idcard 可选 string 身份证号
     * @param status 可选 int 状态状态1正常2冻结
     * @param is_deleted 可选 string 是否删除1是0否
     * @return {"code": 0, "message": "操作成功", "data": ""}
     * @remark
     * @number 0
     * @author lcx
     * @date 2020-02-12
     */
    public function register()
    {
        if (empty($this->parm['company_id'])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "缺少参数company_id");
        }
        if (empty($this->parm['app_sn'])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "缺少参数app_sn");
        }
        if (empty($this->parm['client'])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "缺少参数client");
        }
        if (empty($this->parm['telphone'])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "请填写手机号");
        }
        if (!isMobile($this->parm['telphone'])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "手机号不正确,请确认");
        }
        //判断企业是否存在
        $companyInfo = $this->companyModel->getOne(['company_id' => $this->parm['company_id']], 'company_id');
        if (empty($companyInfo)) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "不存在该企业信息");
        }

        //判断终端是否存在
        $system0penClientConfig = config('api.system_open_client');
        if (empty($system0penClientConfig[$this->parm['client']])) {
            returnJson(ReturnCodeService::ILLEGAL_PARAM, "不存在该终端");
        }

        //更新用户信息:判断手机号是否存在,存在更新，反之新增
        $userInfo = $this->userModel->getOne(['telphone' => $this->parm['telphone'], 'company_id' => $this->parm['company_id'], 'is_deleted' => 0], 'id,account,telphone,uuid');
        Db::startTrans();
        try {
            if (empty($userInfo)) {
                $addData['company_id'] = $this->parm['company_id'];
                $addData['account'] = $this->createUserAccount('', 8);
                $addData['telphone'] = $this->parm['telphone'] ?? '';
                $addData['realname'] = $this->parm['realname'] ?? '';
                $addData['sex'] = $this->parm['sex'] ?? 0;
                $addData['idcard'] = $this->parm['idcard'] ?? '';
                $addData['status'] = $this->parm['status'] ?? 1;
                $addData['is_deleted'] = $this->parm['is_deleted'] ?? 0;
                $addData['create_time'] = time();
                $addData['uuid'] = createUuid();//生成uuid
                $userId = $this->userModel->add($addData);

                //添加用户访问信息
                $addVisitData['app_sn'] = $this->parm['app_sn'];
                $addVisitData['client'] = $this->parm['client'];
                $addVisitData['create_time'] = time();
                $addVisitData['uuid'] = $addData['uuid'];
                $this->userVisitModel->add($addVisitData);
                $uuid = $addData['uuid'];
                $account = $addData['account'];
                $telphone = $addData['telphone'];
            } else {
                //更新用户访问信息
                $visitInfo = $this->userVisitModel->getOne(['uuid' => $userInfo['uuid'], 'app_sn' => $this->parm['app_sn'], 'client' => $this->parm['client']], 'id');
                if (empty($visitInfo)) {
                    $addVisitData['app_sn'] = $this->parm['app_sn'];
                    $addVisitData['client'] = $this->parm['client'];
                    $addVisitData['create_time'] = time();
                    $addVisitData['uuid'] = $userInfo['uuid'];
                    $this->userVisitModel->add($addVisitData);
                }
                $uuid = $userInfo['uuid'];
                $account = $userInfo['account'];
                $telphone = $userInfo['telphone'];
            }
            // 事务提交
            Db::commit();
            $key = config('api.jwt_token_key');
            //用户已经存在
            $user_token = [
                'uuid' => $uuid,//用户uuid
                'expire' => time() + 86400 * 15,
                'account' => $account,
                'telphone' => $telphone
            ];
            //生成token
            $token = JWT::encode($user_token, $key, 'HS256');
            returnJson(ReturnCodeService::SUCCESS, "操作成功", ['token' => $token]);

        } catch (\Exception $e) {
            // 事务回滚
            Db::rollback();
            returnJson(ReturnCodeService::SUCCESS, "操作失败!" . $e->getMessage());
        }


    }

//if (!empty($this->parm['realname'])) {
//$editData['realname'] = $this->parm['realname'];
//}
//if (!empty($this->parm['sex'])) {
//    $editData['sex'] = $this->parm['sex'];
//}
//if (!empty($this->parm['idcard'])) {
//    $editData['idcard'] = $this->parm['idcard'];
//}
//if (!empty($this->parm['status'])) {
//    $editData['status'] = $this->parm['status'];
//}
//if (!empty($this->parm['is_deleted'])) {
//    $editData['is_deleted'] = $this->parm['is_deleted'];
//}
//$editData['update_time'] = time();
//$this->userModel->edit(['id' => $userInfo['id']], $editData);

    //创建用户账号
    public function createUserAccount($prefix = '', $length = 8)
    {
        $arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $arr[rand(0, 9)];
        }
        //判断唯一性
        $userInfo = $this->userModel->getOne(['account' => $str, 'is_deleted' => 0], 'account');

        if (!empty($userInfo)) {
            $this->createUserAccount('', $length);
        } else {
            return $str;
        }
    }
}